#pragma once

#include <iostream>
#include <string>
#include <vector>
#include <fstream>
#include <mutex>
#include <cassert>
#include <jsoncpp/json/json.h>

#include "../comm/util.hpp"
#include "../comm/log.hpp"
#include "../comm/httplib.h"
#include "oj_model.hpp"
#include "oj_view.hpp"

namespace ns_control
{
    using namespace std;
    using namespace ns_log;
    using namespace ns_util;
    using namespace ns_model;
    using namespace ns_view;
    using namespace httplib;

    // 提供服务主机
    class Machine
    {
    public:
        std::string ip;  // 编译服务的ip
        int port;        // 编译服务的port
        uint64_t load;   // 编译服务的负载
        std::mutex *mtx; // C++的mutex禁止拷贝
    public:
        Machine() : ip(""), port(0), load(0), mtx(nullptr)
        {
        }
        ~Machine()
        {
        }

    public:
        // 提升主机负载
        void InLoad()
        {
            if (mtx)
                mtx->lock();
            ++load;
            if (mtx)
                mtx->unlock();
        }
        // 减少主机负载
        void DecLoad()
        {
            if (mtx)
                mtx->lock();
            --load;
            if (mtx)
                mtx->unlock();
        }
        void ResetLoad()
        {
            if(mtx) mtx->lock();
            load = 0;
            if(mtx) mtx->unlock();
        }
        // 获取主机负载
        uint64_t Load()
        {
            uint64_t _load = 0;
            if (mtx)
                mtx->lock();
            _load = load;
            if (mtx)
                mtx->unlock();

            return _load;
        }
    };

    const std::string service_machine = "./conf/service_machine.conf";

    // 负载均衡模块
    class LoadBlance
    {
    private:
        std::vector<Machine> machines; // 可以提供编译服务的所有主机
        std::vector<int> online;       // 所有在线主机的id
        std::vector<int> offline;      // 所有离线主机的id
        std::mutex mtx;

    public:
        LoadBlance()
        {
            assert(LoadConf(service_machine));
            LOG(INFO) << "加载: " << service_machine << " 成功" << "\n";
        }
        ~LoadBlance()
        {
        }

    public:
        bool LoadConf(const std::string &machine_conf)
        {
            std::ifstream in(machine_conf);
            if (!in.is_open())
            {
                LOG(FATAL) << "加载: " << machine_conf << " 失败" << "\n";
                return false;
            }

            std::string line;
            while (std::getline(in, line))
            {
                std::vector<std::string> tokens;
                StringUtil::SplitString(line, &tokens, ":");
                if (tokens.size() != 2)
                {
                    LOG(WARNING) << " 切分 " << line << " 失败" << "\n";
                    continue;
                }

                Machine m;
                m.ip = tokens[0];
                m.port = atoi(tokens[1].c_str());
                m.load = 0;
                m.mtx = new std::mutex;

                online.push_back(machines.size());
                machines.push_back(m);
            }

            in.close();
            return true;
        }
        // 智能选择一台主机进行提供编译服务
        bool SmartChoice(int *id, Machine **m)
        {
            mtx.lock();
            // 负载均衡算法
            // 1. 随机数法 + hash
            // 2. 轮询 + hash
            int online_num = online.size(); // 所有在线主机的总个数
            if (online_num == 0)
            {
                mtx.unlock();
                LOG(FATAL) << "所有的后端编译主机已经离线,请运维的同事尽快查看" << "\n";
                return false;
            }

            // 走到下面说明至少存在一台主机处于在线状态
            // 通过遍历方式找到负载最小的主机用于进行编译
            *id = online[0];
            *m = &machines[online[0]];
            uint64_t min_load = machines[online[0]].load;
            for (int i = 0; i < online_num; i++)
            {
                uint64_t curr_load = machines[online[i]].load;
                if (min_load > curr_load)
                {
                    min_load = curr_load;
                    *id = online[i];
                    *m = &machines[online[i]];
                }
            }
            mtx.unlock();
            return true;
        }
        // 上线主机
        void OnlineMachine()
        {
            // 规则:只有当所有的主机离线时,才上线主机
            mtx.lock();
            online.insert(online.end(), offline.begin(), offline.end());
            offline.erase(offline.begin(), offline.end());
            mtx.unlock();

            LOG(INFO) << "所有主机又上线 " << "\n";
        }
        // 离线主机
        void OfflineMachine(int which)
        {
            mtx.lock();
            for (auto iter = online.begin(); iter != online.end(); iter++)
            {
                if (*iter == which)
                {
                    machines[which].ResetLoad();
                    // 离线主机存在
                    offline.push_back(*iter); // 先添加，再删除，防止iter迭代器失效
                    online.erase(iter);
                    break;
                }
            }

            mtx.unlock();
        }
        void ShowMachines()
        {
            mtx.lock();
            LOG(INFO) << "当前在线主机列表: ";
            for (auto &id : online)
            {
                std::cout << id << " ";
            }
            std::cout << std::endl;

            LOG(INFO) << "当前离线主机列表: ";
            for (auto &id : offline)
            {
                std::cout << id << " ";
            }
            std::cout << std::endl;
            mtx.unlock();
        }
    };

    // 核心业务逻辑的控制器
    class Control
    {
    private:
        Model model_; // 提供后台数据
        View view_;   // 提供网页
        LoadBlance load_blance;

    public:
        Control()
        {
        }
        ~Control()
        {
        }

    public:
        void RecoveryMachine()
        {
            
            load_blance.OnlineMachine();
        }
        // html:输出型参数
        bool AllQuestions(string *html)
        {
            vector<struct Question> all;
            bool ret = true;
            if (model_.GetAllQuestions(&all))
            {
                sort(all.begin(), all.end(), [](const struct Question &q1, const struct Question &q2)
                     { return atoi(q1.number.c_str()) < atoi(q2.number.c_str()); });

                // 获取题库成功,将所有题库中的数据渲染成网页
                view_.AllExpandHtml(all, html);
            }
            else
            {
                *html = "获取题库失败,形成题目列表失败";
                ret = false;
            }

            return ret;
        }
        bool Question(const string &number, string *html)
        {
            bool ret = true;
            struct Question q;
            if (model_.GetOneQuestion(number, &q))
            {
                // 获取指定的题成功,将指定的题渲染成网页
                view_.OneExpandHtml(q, html);
            }
            else
            {
                *html = "指定题目: " + number + "不存在!";
                ret = false;
            }

            return ret;
        }

        void Judge(const std::string &number, const std::string in_json, std::string *out_json)
        {
            LOG(DEBUG) << in_json << "\nnumber: " << number << "\n";
            // 根据题目的编号拿到对应题目的具体情况
            struct Question q;
            model_.GetOneQuestion(number, &q);
            // 1. 对in_json进行反序列化,的带题目的id及用户源代码
            Json::Reader reader;
            Json::Value in_value;
            reader.parse(in_json, in_value);
            std::string code = in_value["code"].asString();
            // 2. 拼接用户的代码和测试用例代码
            Json::Value compile_value;
            compile_value["input"] = in_value["input"].asString();
            compile_value["code"] = code + q.tail;
            compile_value["cpu_limit"] = q.cpu_limit;
            compile_value["mem_limit"] = q.mem_limit;
            Json::FastWriter writer;
            std::string compile_string = writer.write(compile_value);
            // 3. 选择负载低的主机
            while (true)
            {
                int id = 0;
                Machine *m = nullptr;
                if (!load_blance.SmartChoice(&id, &m))
                {
                    break;
                }
                LOG(INFO) << "选择主机成功,主机id: " << id << "详情: " << m->ip << ":" << m->port << "\n";
                // 4. 发起http请求服务,得到对应的结果
                Client cli(m->ip, m->port);
                m->InLoad();
                if (auto res = cli.Post("./compile_and_run", compile_string, "application/json;charset=utf-8"))
                {
                    // 5. 请求成功,将结果赋值给out_json
                    if (res->status == 200)
                    {
                        *out_json = res->body;
                        m->DecLoad();
                        LOG() << "请求编译和运行服务成功..." << "\n";
                        break;
                    }
                    m->DecLoad();
                }
                else
                {
                    // 请求失败了
                    LOG(ERROR) << "当前选择主机id: " << id << "详情: " << m->ip << ":" << m->port << "可能已经离线" << "\n";
                    m->InLoad();
                    load_blance.OfflineMachine(id); // 离线该主机
                    load_blance.ShowMachines();
                }
            }
        }
    };
}